package fxmedia.ui;

// Import JavaFX Classes
import javafx.event.EventHandler;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;

// Import Application classes
import fxmedia.Constants;
import fxmedia.FxMedia;

/**
 * @author dca
 */
public class PreviousButton extends Label {
	/**
	 * Constructs the previous-track button.<br/>
	 * @param app The media player application.<br/>
	 */
	public PreviousButton(final FxMedia app) {
		super();
		this.setDisable(true); // This is re-enabled from LibraryList::initSelectionListener(FxMedia)
		setGraphic(new ImageView(new Image(FxMedia.class.getResourceAsStream(Constants.PREVIOUS_TRACK_IMAGE_PATH))));
		this.initMouseClickListener(app);
	} // END constructor

	/**
	 * Adds a listener to detect mouse clicks on the previous button.<br/>
	 * @param app The media player application.<br/>
	 */
	private void initMouseClickListener(final FxMedia app) {
		this.setOnMouseClicked(new EventHandler<MouseEvent>() {
			@Override
			public void handle(MouseEvent me) {
				playPreviousSelection(app);
			} // END handle
		}); // END setOnMouseClicked
	} // END initMouseClickListener

	/**
	 * plays the song that&apos;s before the highlighted song in the library.<br/>
	 * Also, updates the track information within the application.<br/>
	 * @param app The media player application.<br/>
	 */
	public void playPreviousSelection(final FxMedia app) {
		boolean shuffling = OrderButton.State.SHUFFLE_TRACKS == app.getOrderTracksButton().getState();
		final int index = app.getLibraryList().getPreviousTrackIndex(shuffling);
		app.getLibraryList().selectAndScrollTo(index);

		if(PlayButton.State.PUSH_TO_STOP == app.getPlayTrackButton().getState() || app.getPlayer().isPlaying()) {
			app.getPlayer().stop();
			app.getPlayTrackButton().playCurrentSelection(app);
		} // END if
	} // END playPreviousSelection
} // END class PreviousButton
